import * as THREE from 'three';
import {MoveLookAtControls} from '../../js/MoveLookAtControls.js'
import Stats from 'three/examples/jsm/libs/stats.module.js';


import {baseUrl} from '../../js/base.js'
import '../../css/base.css'
import pl from "element-ui/src/locale/lang/pl";

let canvas = document.getElementById("canvas")
let renderer, scene, camera;
let moveDirectionControls;

let peopleH = 1.8
let cameraP = new THREE.Vector3(0, peopleH, 20);

let mouse = new THREE.Vector2(), cursor = null;
let raycaster = new THREE.Raycaster();
let startEuler = new THREE.Euler();

const stats = new Stats()
document.body.appendChild(stats.domElement)

function initCSR() {
  const w = canvas.offsetWidth || window.innerWidth;
  const h = canvas.offsetHeight || window.innerHeight;

  camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 10000)
  camera.position.set(...Object.values(cameraP))
  cameraP = camera.position

  scene = new THREE.Scene()

  renderer = new THREE.WebGLRenderer({canvas, antialias: true, alpha: true});
  camera.updateProjectionMatrix();
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(w, h, false)
}

function initLight() {
  const ambientLight = new THREE.AmbientLight(0xffffff, .2);
  scene.add(ambientLight)

  const hemisphereLight = new THREE.HemisphereLight(0xaaaaaa, .5);
  scene.add(hemisphereLight)

  const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
  directionalLight.position.set(1, 1, 1)
  scene.add(directionalLight)
}

function initModel() {
  let textureLoader = new THREE.TextureLoader();
  let texture = textureLoader.load(baseUrl + 'static/images/floor.jpeg')
  texture.wrapS = texture.wrapT = THREE.MirroredRepeatWrapping
  texture.repeat.set(32, 32)
  const geometry = new THREE.PlaneGeometry(100, 100, 100);
  const material = new THREE.MeshPhongMaterial({color: 0x909399, map: texture, side: THREE.DoubleSide});

  const floor = new THREE.Mesh(geometry, material);
  floor.name = 'floor'
  geometry.rotateX(Math.PI / 2)
  scene.add(floor);

  const cursorTexture = textureLoader.load(baseUrl + 'static/images/pointer.png')
  const meshBasicMaterial = new THREE.MeshBasicMaterial({map: cursorTexture, depthTest: false, transparent: true, opacity: .8, side: THREE.DoubleSide});
  const planeGeometry = new THREE.PlaneGeometry();
  planeGeometry.rotateX(Math.PI / 2)
  cursor = new THREE.Mesh(planeGeometry, meshBasicMaterial)
  cursor.name = 'floor'
  floor.add(cursor)

  const geometryBox = new THREE.BoxBufferGeometry(2, 2, 2);

  for (let i = 0; i < 500; i++) {
    const materialBox = new THREE.MeshPhongMaterial(
      {color: new THREE.Color(Math.random(), Math.random(), Math.random())});
    const meshBox = new THREE.Mesh(geometryBox, materialBox);
    meshBox.name = 'hot_' + i
    meshBox.position.set(
      Math.round(Math.random() * 60) - 30,
      Math.round(Math.random() * 30) + 1,
      Math.round(Math.random() * 60) - 30
    )
    scene.add(meshBox);
  }

}

function initControls() {
  moveDirectionControls = new MoveLookAtControls(camera, canvas);
  moveDirectionControls.startFun = function(e) {
    mouse.x = (e.offsetX / canvas.offsetWidth) * 2 - 1;
    mouse.y = -(e.offsetY / canvas.offsetHeight) * 2 + 1;
    startEuler.copy(moveDirectionControls.getObject().rotation)
  }
  moveDirectionControls.moveFun = function(e) {
    mouse.x = (e.offsetX / canvas.offsetWidth) * 2 - 1;
    mouse.y = -(e.offsetY / canvas.offsetHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);
    let intersectObjects = raycaster.intersectObjects(scene.children, true);
    if (intersectObjects.length && intersectObjects[0].object.name === 'floor') {
      cursor.material.visible = true
      cursor.position.copy(intersectObjects[0].point)
    } else {
      cursor.material.visible = false
    }
  }
  moveDirectionControls.endFun = function(e) {
    if (startEuler.equals(moveDirectionControls.getObject().rotation)) {
      raycaster.setFromCamera(mouse, camera);
      let intersectObjects = raycaster.intersectObjects(scene.children, true);
      if (intersectObjects.length && intersectObjects[0].object.name === 'floor') {
        moveDirectionControls.fromMoveTo(moveDirectionControls.getObject().position,
          {x: intersectObjects[0].point.x, y: intersectObjects[0].point.y + peopleH, z: intersectObjects[0].point.z}, 1000)
      } else if (intersectObjects.length && intersectObjects[0].object.name.indexOf('hot') > -1) {
        confirm(`你点击了模型: ${intersectObjects[0].object.name}`)
      }
    }
  }
}

function onWindowResize() {
  const width = canvas.offsetWidth;
  const height = canvas.offsetHeight;
  camera.aspect = width / height;
  renderer.setSize(width, height, false);
  camera.updateProjectionMatrix();
} // 控制窗口大小

function render() {
  if (moveDirectionControls) moveDirectionControls.update();

  renderer.render(scene, camera)
  stats.update();
}

function animation() {
  requestAnimationFrame(animation)
  render()
}

(async() => {
  initCSR();
  initLight();
  initModel();
  initControls();
  animation();
  window.addEventListener('resize', onWindowResize);
  setInterval(() => {
    // console.log(camera.position);
    // console.log(moveDirectionControls.getPosition())
    // console.log(camera.position.equals(moveDirectionControls.getPosition()))
    // console.log(moveDirectionControls.getDirection())
  }, 2000)
})();

